//
//  HWPushDynamicViewController.swift
//  HWanGame
//
//  Created by Apple on 2024/8/22.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import Stevia
import IQKeyboardManagerSwift
import ZLPhotoBrowser
import Photos

class HWPushDynamicViewController: HWBaseViewController {

    private let scrollView = UIScrollView()
    private let containerView = UIView()
    private let closeButton = c_make_ex(UIButton.self)
        .image("Report_close").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("发布到圈子").font(16.font_semiBold).color(.black).end()
    private let sendButton = c_make_ex(UIButton.self)
        .image("Push_dynamicSendSel").image("Push_dynamicSendNor", state: .disabled).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(18*widthScale).border(.black.alpha(0.1), width: 1.5).end()
    private let placeholderLabel = c_make_ex(UILabel.self)
        .text("在此处键入内容...").font(15.font_medium).color("#AEB0B3").end()
    // 创建UITextView
    private let textView: UITextView = {
        let tv = UITextView()
        tv.font = 15.font_medium
        tv.textColor = "#47494D".toColor
        tv.tintColor = "#47494D".toColor
        tv.isScrollEnabled = false  // 禁止滚动
        tv.backgroundColor = .clear
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()
    private let functionView = DynamicFunctionView()
    private let searchView = DynamicSearchView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    let httpManager = HWGameCircleHttpManager()
    var gameModels: [HWDynamicGameModel]?
    var topicModels: [HWDynamicGameModel]?
    
    private var hasVideo = false
    private var images: [UIImage] = []
    private var assets: [PHAsset] = []
    
    init() {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationView.isHidden = true
        view.backgroundColor = "#F7F8FA".toColor
        
        loadData()
        
        view.subviews{
            scrollView.subviews{
                containerView.subviews{
                    closeButton
                    titleLabel
                    sendButton
                    iconImageView
                    textView.subviews{
                        placeholderLabel
                    }
                    searchView
                    functionView
                    collectionView
                }
            }
        }
        
        scrollView.backgroundColor = .clear
        containerView.backgroundColor = .clear
        scrollView.top(0).leading(0).width(.screenWidth).bottom(0)
        containerView.fillContainer().width(.screenWidth)
        closeButton.top(.statusHeight).leading(0).width(56*widthScale).height(44*widthScale)
        titleLabel.Leading == closeButton.Trailing
        titleLabel.CenterY == closeButton.CenterY
        sendButton.trailing(0).top(.statusHeight).height(44*widthScale).width(88*widthScale)
        iconImageView.leading(10).top(.navi_height+4.0).size(36*widthScale)
        textView.leading(56*widthScale).trailing(12*widthScale).top(.navi_height+8*widthScale).height(37*widthScale)
        placeholderLabel.leading(2).top(2)
        functionView.leading(56*widthScale).trailing(0).height(33*widthScale)
        functionView.Top == textView.Bottom + 3*widthScale
        searchView.leading(56*widthScale).trailing(12*widthScale).height(290*widthScale)
        searchView.Top == textView.Bottom + 5*widthScale
        collectionView.leading(0).trailing(0).height(0).bottom(.tabBar_height)
        collectionView.Top == functionView.Bottom + 8*widthScale
        
        sendButton.isEnabled = false
        textView.delegate = self
        searchView.isHidden = true
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        functionView.imgStr = ["Dynamic_game","Dynamic_topic","Dynamic_pic"]
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = true
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 2*widthScale
        layout.minimumInteritemSpacing = 2*widthScale
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 0, left: 56*widthScale, bottom: 0, right: 16*widthScale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(HWGameCircleCell.self, forCellWithReuseIdentifier: HWGameCircleCell.description())
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        functionView.functionButtonBlock = { funcID in
            
            if funcID == 0 {
                
                self.searchView.isHidden = false
                self.functionView.isHidden = true
                self.searchView.dataModel = self.gameModels
                
            } else if funcID == 1 {
                
                self.searchView.isHidden = false
                self.functionView.isHidden = true
                self.searchView.dataModel = self.topicModels
            } else if funcID == 2 {
                
                self.showPhotoLibrary()
            }
            
            self.textView.resignFirstResponder()
        }
        
        searchView.searchBlock = { md in
            
            if !self.searchView.isHidden {
                self.searchView.isHidden = true
                self.functionView.isHidden = false
            }
            if md.type == "2" {
                //游戏
                self.insertRichText(in: self.textView, image: "Dynamic_gameTag".toImage, text: md.name, textColor: "#3D9399".toColor, imageSize: CGSizeMake(20, 20))
                self.textView.becomeFirstResponder()
            }else {
                //话题
                self.insertRichText(in: self.textView, image: nil, text: "#" + md.name, textColor: "#E57617".toColor, imageSize: .zero)
                self.textView.becomeFirstResponder()
            }
        }
    }
    
    
    @objc private func clickCloseButton(){
        self.dismiss(animated: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        if !searchView.isHidden {
            self.searchView.isHidden = true
            self.functionView.isHidden = false
        }
    }
}

//MARK: Action
extension HWPushDynamicViewController {
    
    func showPhotoLibrary() {
        if hasVideo {
            self.view.showHUD(title: "请删除视频后重选")
            return
        }
        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
        config.maxSelectCount = 9
        config.allowSelectGif = false
        config.allowMixSelect = false
        config.allowSelectVideo = images.count == 0
        config.allowTakePhotoInLibrary = true
        config.allowEditVideo = true
        config.maxEditVideoTime = 30
        config.maxRecordDuration = 30
        config.editAfterSelectThumbnailImage = true
        config.allowSelectOriginal = false
        config.animateSelectBtnWhenSelect = false
        config.cropVideoAfterSelectThumbnail = true
        let ac = ZLPhotoPreviewSheet(selectedAssets:assets)
        
        ac.selectImageBlock = { [weak self] (images, assets, isOriginal) in
            self?.hasVideo = assets.first?.mediaType == .video
            self?.images = images
            self?.assets = assets
            self?.loadImageData()
        }
        ac.showPhotoLibrary(sender: self)
    }
}

//MARK: TextView
extension HWPushDynamicViewController: UITextViewDelegate {
    
    // UITextViewDelegate 方法
    func textViewDidChange(_ textView: UITextView) {
        // 计算文本内容的高度
        let size = CGSize(width: textView.frame.width, height: .infinity)
        let estimatedSize = textView.sizeThatFits(size)
        // 更新高度约束
        textView.heightConstraint?.constant = estimatedSize.height
        
        // 根据内容决定是否隐藏占位符
        placeholderLabel.isHidden = !textView.text.isEmpty
        sendButton.isEnabled = textView.text.isEmpty
        changeToRichText(textView)
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        // 开始编辑时隐藏占位符
        placeholderLabel.isHidden = true
    }
        
    func textViewDidEndEditing(_ textView: UITextView) {
        // 结束编辑时，如果内容为空，显示占位符
        if textView.text.isEmpty {
            placeholderLabel.isHidden = false
        }
    }
    
    func changeToRichText(_ textView: UITextView){
        
        // 获取光标的位置
        guard let selectedRange = textView.selectedTextRange else { return }
            
        // 保存当前的 attributedText
        let currentAttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
            
        // 获取新增的文本（未设置样式的文本）
        let range = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
        let inputRange = NSRange(location: range - 1, length: 1)
            
        // 获取新输入的字符
        let newInput = (textView.text as NSString).substring(with: inputRange)
            
        // 设置新输入字符的默认样式
        let newAttributedString = NSAttributedString(string: newInput, attributes: [
            .font: 15.font_medium!,
            .foregroundColor: "#47494D".toColor
        ])
            
        // 替换未设置样式的文本
        currentAttributedText.replaceCharacters(in: inputRange, with: newAttributedString)
            
        // 更新 textView 的 attributedText
        textView.attributedText = currentAttributedText
            
        // 恢复光标位置
        if let newPosition = textView.position(from: textView.beginningOfDocument, offset: range) {
            textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition)
        }
    }
    
    func insertRichText(in textView: UITextView, image: UIImage?, text: String, textColor: UIColor, imageSize: CGSize) {
        // 创建富文本
        let richText = NSMutableAttributedString()

        // 添加现有内容
        if let currentText = textView.attributedText {
            richText.append(currentText)
        }

        // 插入图片
        if let image = image {
            let attachment = NSTextAttachment()
            attachment.image = image
            attachment.bounds = CGRect(origin: .zero, size: imageSize)
            attachment.bounds = CGRect(x: 0, y: -5, width: imageSize.width, height: imageSize.height)
            let imageString = NSAttributedString(attachment: attachment)
            richText.append(imageString)
        }

        // 插入文本
        let attributedText = NSAttributedString(string: text, attributes: [.foregroundColor: textColor])
        richText.append(attributedText)
        
        // 保持现有的字体设置
        let entireRange = NSRange(location: 0, length: richText.length)
        richText.addAttribute(.font, value: 15.font_medium!, range: entireRange)

        // 插入后的光标位置
        let newCursorPosition = richText.length

        // 更新UITextView的内容并设置光标位置
        textView.attributedText = richText
        if let newPosition = textView.position(from: textView.beginningOfDocument, offset: newCursorPosition) {
            textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition)
        }
    }

}

//MARK: TextView
extension HWPushDynamicViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if hasVideo {
            return 1
        }else{
            return images.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let pageCell = collectionView.dequeueReusableCell(withReuseIdentifier: HWGameCircleCell.description(), for: indexPath) as? HWGameCircleCell else { return UICollectionViewCell() }
        pageCell.imageView.image = images[indexPath.row]
        pageCell.playImage.isHidden = !hasVideo
        pageCell.index = indexPath.row
        pageCell.delButton.isHidden = false
        pageCell.delBlock = { delIndex in
            self.images.remove(at: delIndex)
            self.assets.remove(at: delIndex)
            self.hasVideo = false
            self.collectionView.reloadData()
        }
        pageCell.layoutIfNeeded()
        if images.count == 1 {
            pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 8*widthScale)
        }else if images.count == 2 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8*widthScale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 3 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8*widthScale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8*widthScale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 4 || images.count == 5{
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8*widthScale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8*widthScale)
            }else if indexPath.row == 3 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8*widthScale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
            
        }else if images.count == 6 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8*widthScale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8*widthScale)
            }else if indexPath.row == 3 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8*widthScale)
            }else if indexPath.row == 5 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8*widthScale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 7 || images.count == 8{
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8*widthScale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8*widthScale)
            }else if indexPath.row == 6 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8*widthScale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8*widthScale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8*widthScale)
            }else if indexPath.row == 6 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8*widthScale)
            }else if indexPath.row == 8 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8*widthScale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }
        
        return pageCell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if hasVideo {
            return CGSize (width: CGFloat.screenWidth - 104*widthScale, height: 152*widthScale)
        }else if images.count == 1 {
            return CGSize (width: CGFloat.screenWidth - 104*widthScale, height: 152*widthScale)
        }else if images.count == 2{
            
            return CGSize (width: (CGFloat.screenWidth - 74.0*widthScale)/2, height: 90*widthScale)
        }else{
            
            return CGSize (width: (CGFloat.screenWidth - 76.0*widthScale)/3, height: (CGFloat.screenWidth - 76.0*widthScale)/3)
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let vc = ZLImagePreviewController(datas: self.assets, index: indexPath.row, showSelectBtn: false) { (url) -> ZLURLType in
            if self.hasVideo {
                return .video
            }else {
                return .image
            }
            
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
}


//MARK: data
extension HWPushDynamicViewController {
    
    private func loadData(){
        
        self.httpManager.dynamicSearchTopic(keyword: "") { modelArr in

            var tempModels = [HWDynamicGameModel]()
            for md in modelArr {
                md.type = "1"
                tempModels.append(md)
            }
            self.topicModels = tempModels
        } failure: { error in
            self.showHUDWithError(msg: error)
        }
        
        self.httpManager.dynamicSearchGame(keyword: "") { modelArr in

            var tempModels = [HWDynamicGameModel]()
            for md in modelArr {
                md.type = "2"
                tempModels.append(md)
            }
            self.gameModels = tempModels            
        } failure: { error in
            self.showHUDWithError(msg: error)
        }
    }
    
    private func loadImageData(){
        
        if hasVideo {
            
            collectionView.heightConstraint?.constant = 152*widthScale
        }else {
            
            if images.count == 1 {
                collectionView.heightConstraint?.constant = 152*widthScale
            }else if images.count == 2 {
                collectionView.heightConstraint?.constant = 90*widthScale
            }else if images.count > 2 {
                let index = (images.count + 2) / 3
                collectionView.heightConstraint?.constant = (CGFloat.screenWidth - 76.0*widthScale)/3 * CGFloat(index)
            }else{
                collectionView.heightConstraint?.constant = 0
            }
        }
        collectionView.reloadData()
    }
}

